<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-input
          v-model="queryParams.grade"
          placeholder="请输入年级"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班主任ID" prop="uid">
        <el-input
          v-model="queryParams.uid"
          placeholder="请输入班主任ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程ID" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入课程ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="创建时间" prop="createtime">
        <el-date-picker clearable
          v-model="queryParams.createtime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatetime">
        <el-date-picker clearable
          v-model="queryParams.updatetime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="现有容量" prop="current">
        <el-input
          v-model="queryParams.current"
          placeholder="请输入现有容量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="最大容量" prop="capacity">
        <el-input
          v-model="queryParams.capacity"
          placeholder="请输入最大容量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="最佳容量" prop="bestCapacity">
        <el-input
          v-model="queryParams.bestCapacity"
          placeholder="请输入最佳容量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tbclass:tbclass:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tbclass:tbclass:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tbclass:tbclass:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tbclass:tbclass:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tbclassList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级ID" align="center" prop="classId" />
      <el-table-column label="班级名称" align="center" prop="name" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="班主任ID" align="center" prop="uid" />
      <el-table-column label="课程" align="center" prop="courseName">
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'warning'">{{ scope.row.status === 0 ? '正常' : '停用' }}</el-tag>
        </template>
      </el-table-column>
      <!-- 上课时间和下课时间，是Localtime -->
       <el-table-column label="上课时间" align="center" prop="startTime">
        <template #default="scope">
          {{ formatTime(scope.row.startTime) }}
        </template>
       </el-table-column>
       <el-table-column label="下课时间" align="center" prop="endTime">
        <template #default="scope">
          {{ formatTime(scope.row.endTime) }}
        </template>
       </el-table-column>
      <!-- 提供一个详情按钮，根据班级ID查询班级详情信息，点击按钮弹出对话框显示详情信息，包含创建时间、更新时间、最佳容量、最大容量 -->
      <el-table-column label="班级详情信息" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleDetail(scope.row)">点击查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tbclass:tbclass:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tbclass:tbclass:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tbclassRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入年级" />
        </el-form-item>
        <el-form-item label="班主任" prop="uid">
          <el-select v-model="form.uid" placeholder="请选择班主任">
            <el-option v-for="item in teacherList" :key="item.userId" :label="item.userName" :value="item.userId">{{item.userName  }}</el-option>
          </el-select>  
        </el-form-item>
        <!-- 和课程表关联，需要提供课程ID 只能选择一个课程-->
        <el-form-item label="课程" prop="courseName">
          <el-select v-model="form.courseId" placeholder="请选择课程">
            <el-option v-for="item in couresList" :key="item.courseId" :label="item.courseName" :value="item.courseId">{{item.courseName  }}</el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="最大容量" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入最大容量" />
        </el-form-item>
        <el-form-item label="最佳容量" prop="bestCapacity">
          <el-input v-model="form.bestCapacity" placeholder="请输入最佳容量" />
        </el-form-item>
        <el-form-item label="上课时间" prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="请选择上课时间"
            value-format="HH:mm:ss"
            :picker-options="{
              start: '08:00',  // 最早可选时间
              step: '00:30',   // 时间间隔
              end: '22:00'     // 最晚可选时间
            }"
            class="custom-time-picker"
          />
        </el-form-item>
        <el-form-item label="下课时间" prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            placeholder="请选择下课时间"
            value-format="HH:mm:ss"
            :picker-options="{
              start: '08:00',  
              step: '00:30',   
              end: '22:00'     
            }"
            class="custom-time-picker"
          />
        </el-form-item>

         <!-- 不使用字典 状态 -->
        <el-form-item label="状态" prop="status" >
          <el-select v-model="form.status" placeholder="请选择状态,默认为正常">
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
         </el-form-item> 
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tbclass">
import { listTbclass, getTbclass, delTbclass, addTbclass, updateTbclass } from "@/api/tbclass/tbclass"
import { ElMessageBox, ElMessage } from 'element-plus'
import dayjs from 'dayjs' // 可选：时间格式化，需安装 dayjs
import { status } from "nprogress"
import { listTbcourse } from "@/api/tbcourse/tbcourse"
import {listTeacher} from "@/api/system/user"

const { proxy } = getCurrentInstance()
const {sys_basic_status} = proxy.useDict("sys_basic_status")
const tbclassList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const couresList = ref([])
const teacherList = ref([])



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    grade: null,
    uid: null,
    courseId: null,
    status: null,
    createtime: null,
    updatetime: null,
    current: null,
    capacity: null,
    bestCapacity: null,
    startTime: null,
    endTime: null,
    courseName: null
  },
  // 下课时间不能早于上课时间
  rules: {
    name: [
      { required: true, message: "班级名称不能为空", trigger: "blur" }
    ],
    courseId: [
      { required: true, message: "课程ID不能为空", trigger: "blur" }
    ],
    courseName: [
      { required: true, message: "课程不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "上课时间不能为空", trigger: "change" }
    ],
    // 下课时间不能为空,且不能早于上课时间
    endTime: [
      { required: true, message: "下课时间不能为空", trigger: "change" },
      { validator: (rule, value, callback) => {
        if (value <= data.form.startTime) {
          callback(new Error("下课时间不能早于上课时间"))
        } else {
          callback()
        }
      }, trigger: "change" }
    ],
    uid: [
      { required: true, message: "班主任不能为空", trigger: "blur" }
    ],
    courseId: [
      { required: true, message: "课程不能为空", trigger: "blur" }
    ],
    
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询班级管理列表 */
function getList() {
  loading.value = true
  // listTbclass(queryParams.value).then(response => {
  listTbclass(queryParams.value).then(response => {
    tbclassList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    classId: null,
    name: null,
    grade: null,
    uid: null,
    courseId: null,
    status: null,
    createtime: null,
    updatetime: null,
    current: null,
    capacity: null,
    bestCapacity: null,
    startTime: null,
    endTime: null
  }
  proxy.resetForm("tbclassRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 获取教师信息
function getTeacherList() {
  listTeacher(queryParams.value).then(response => {
    teacherList.value = response.rows
  })
}
getTeacherList()


/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 获取课程表的信息
function getCourseList() {
  listTbcourse(queryParams.value).then(response => {
    couresList.value = response.rows
  })
}
getCourseList()
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.classId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/**
 * 点击详情按钮 - 弹出包含 row 数据的弹窗
 * @param {Object} row - 表格行数据（scope.row）
 */
 const handleDetail = (row) => {
  try {
    // 1. 时间格式化函数（可选，根据实际需求调整）
    const formatTime = (time) => {
      if (!time) return '无'
      // 示例：转成 "YYYY-MM-DD HH:mm:ss"，可根据字段类型调整
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss') 
      // 如果是 LocalTime（仅时间），可改成：dayjs(time).format('HH:mm:ss')

    }

    // 2. 拼接弹窗内容（直接用 row 里的字段）
    const content = `
      <div style="padding: 16px;">
        <p><strong>班级名称：</strong>${row.name || '无'}</p>
        <p><strong>年级：</strong>${row.grade || '无'}</p>
        <p><strong>班主任ID：</strong>${row.uid || '无'}</p>
        <p><strong>课程ID：</strong>${row.courseId || '无'}</p>
        <p><strong>状态：</strong>${row.status === 0 ? '正常' : row.status === 1 ? '隐藏' : row.status || '无'}</p>
        <p><strong>创建时间：</strong>${formatTime(row.createtime)}</p>
        <p><strong>更新时间：</strong>${formatTime(row.updatetime)}</p>
        <p><strong>现有容量：</strong>${row.current || '无'}</p>
        <p><strong>最大容量：</strong>${row.capacity || '无'}</p>
        <p><strong>最佳容量：</strong>${row.bestCapacity || '无'}</p>
      </div>
    `

    // 3. 调用 Element Plus 弹窗
    ElMessageBox({
      title: '班级管理详情',
      message: content,
      dangerouslyUseHTMLString: true, // 允许内容解析 HTML
      type: 'info',
      confirmButtonText: '确定'
    })

    // 4. 提示成功（可选，根据需求决定是否需要）
    // ElMessage.success('详情加载成功')
  } catch (error) {
    // 5. 异常兜底（关闭弹窗时会进入 catch，可根据需求处理）
    ElMessage.error('加载详情失败，请重试')
    console.error('详情弹窗异常：', error)
  }
}

// 时间格式化函数
const formatTime = (timeStr) => {
  if (!timeStr) return '--'
  
  try {
    // 尝试解析多种格式的时间字符串
    const formats = ['HH:mm:ss', 'YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DD HH:mm:ss']
    const parsed = dayjs(timeStr, formats)
    
    if (parsed.isValid()) {
      return parsed.format('HH:mm:ss')
    } else {
      // 格式不匹配时，尝试提取时间部分（适用于带日期的时间戳）
      const timePart = timeStr.split(/[T\s]/)[1]?.split('.')[0]
      return timePart ? dayjs(timePart, 'HH:mm:ss').format('HH:mm:ss') : timeStr
    }
  } catch (error) {
    console.error('时间解析异常:', error)
    return timeStr // 兜底显示原始值
  }
}


/** 新增按钮操作 */
function handleAdd() {
  reset()
  getCourseList()
  getTeacherList()
  open.value = true
  title.value = "添加班级管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _classId = row.classId || ids.value

  form.value = row
  getTbclass(_classId).then(response => {
    form.value = response.data
    if (form.value.status === 0) {
    form.value.status = '正常'
  } else if (form.value.status === 1) {
    form.value.status = '停用'
  }
    open.value = true
    title.value = "修改班级管理"
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["tbclassRef"].validate(valid => {
    if (valid) {
      if (form.value.classId != null) {
        updateTbclass(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTbclass(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _classIds = row.classId || ids.value
  proxy.$modal.confirm('是否确认删除班级管理编号为"' + _classIds + '"的数据项？').then(function() {
    return delTbclass(_classIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tbclass/tbclass/export', {
    ...queryParams.value
  }, `tbclass_${new Date().getTime()}.xlsx`)
}

getList()
</script>
